import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Input, Table, Pagination, message, Popconfirm, Icon, Empty } from 'antd';
import {
  getLogList,
  deleteAllLogs,
  exportLoginLog,
  exportOperateLog,
  showLoginLog,
  showOperateLog,
  downloadOperate,
  downloadLogin,
  deleteLoginLog,
  deleteOperateLog
} from '@api/log';
import ExportModal from '@components/export-modal';
import { connect } from 'react-redux';
import _ from 'lodash';
import './index.less';

const prefixCls = 'OperationalLog';
const Search = Input.Search;
const modeMap = {
  '/log-manage': 'login',
  '/log-manage/login-log': 'login',
  '/log-manage/operational-log': 'operate'
};
const modeNameMap = {
  login: '登录',
  operate: '操作'
};
class OperationalLog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      count: 0,
      filter: {
        type: modeMap[this.props.history.location.pathname],
        page: 1,
        pageSize: 10
      },
      loading: false,
      visible: false,
      mode: modeMap[this.props.history.location.pathname],
      columns: []
    };
  }
  componentDidMount() {
    this.getLogList();
    this.defineTableColumns();
  }
  getLogList = () => {
    const { filter } = this.state;
    this.setState({ loading: true });
    getLogList(filter)
      .then(res => {
        this.setState({
          list: res.data.data.list,
          count: res.data.data.count,
          loading: false
        });
      })
      .catch(() => {
        message.error('获取日志列表失败');
        this.setState({ loading: false });
      });
  };
  //确定表格列名
  defineTableColumns = () => {
    const { mode } = this.state;
    let columns = [];
    const columnsLogin = [
      {
        title: '登录 IP',
        dataIndex: 'ip',
        width: '12%'
      },
      {
        title: '登录结果',
        dataIndex: 'log',
        className: 'detail-wrapper',
        render: this.renderDetail
      },
      {
        title: '登录时间',
        dataIndex: 'created',
        width: 220
      }
    ];

    const columnsOperate = [
      {
        title: '用户名',
        width: '10%',
        dataIndex: 'user_oid.username',
        render: value => <span style={{ whiteSpace: 'nowrap' }}>{value}</span>
      },
      {
        title: '用户类型',
        dataIndex: 'current_role_name',
        width: '10%',
        render: value => <span style={{ whiteSpace: 'nowrap' }}>{value}</span>
      },
      {
        title: '登录 IP',
        dataIndex: 'ip',
        width: '10%'
      },
      {
        title: '模块',
        dataIndex: 'module',
        width: '10%'
      },
      {
        title: '操作描述',
        dataIndex: 'log',
        className: 'detail-wrapper',
        render: this.renderDetail
      },
      {
        title: '登录时间',
        dataIndex: 'created',
        width: 220
      }
    ];

    columns = mode === 'operate' ? columnsOperate : columnsLogin;

    this.setState({ columns });
  };

  renderDetail = value => {
    const { mode } = this.state;
    if (mode === 'login') {
      return (
        <div>
          {value.includes('登录成功') ? (
            <Icon type="check-circle" theme="twoTone" twoToneColor="#52c41a" />
          ) : (
            <Icon type="close-circle" theme="twoTone" twoToneColor="#F04038" />
          )}
          &nbsp;{value}
        </div>
      );
    }
    return <div>{value}</div>;
  };
  // 搜索
  onSearch = value => {
    let { filter } = this.state;
    filter.page = 1;
    filter.search = value;
    this.setState({ filter }, this.getLogList);
  };
  //页码及大小变化
  onPageChange = page => {
    document.getElementsByClassName('ant-layout-content')[0].scrollTop = 0;
    let { filter } = this.state;
    filter.page = page;
    this.setState({ filter }, this.getLogList);
  };
  onShowSizeChange = (current, size) => {
    let { filter } = this.state;
    filter.page = current;
    filter.pageSize = size;
    this.setState({ filter }, this.getLogList);
  };
  //导出弹框
  setExportModalVisible = visible => {
    this.setState({ visible: visible });
  };
  // 删除所有日志
  onDeleteAllLogs = () => {
    deleteAllLogs()
      .then(() => {
        message.success('删除日志成功');
        this.getLogList();
      })
      .catch(({ message: msg }) => {
        if (msg === 'demonstrate forbidden') {
          message.info('演示版本不能删除日志，请联系ZoomEye BE团队获取正式版本');
        } else {
          message.error('删除日志失败');
        }
      });
  };
  render() {
    const { list, count, loading, visible, mode, columns } = this.state;
    const { role } = this.props;
    const exportModalConfig =
      mode === 'operate'
        ? {
            target: '操作日志',
            enableRangePick: true,
            listLoader: showOperateLog,
            downloadDispatcher: exportOperateLog,
            downloader: downloadOperate,
            deleter: deleteOperateLog
          }
        : {
            target: '登录日志',
            enableRangePick: true,
            listLoader: showLoginLog,
            downloadDispatcher: exportLoginLog,
            downloader: downloadLogin,
            deleter: deleteLoginLog
          };

    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-page-title`}>{`${modeNameMap[mode]}日志`}</div>
        <div className={`${prefixCls}-control`}>
          <div>
            <Popconfirm
              title="删除范围是平台所有登录、操作日志。确认删除吗？"
              onConfirm={this.onDeleteAllLogs}
              placement="bottomLeft"
              okText="确认"
              cancelText="取消"
              disabled={role === '审计员' ? true : false}
            >
              <Button
                type="danger"
                style={{ marginRight: 16 }}
                disabled={role === '审计员' ? true : false}
              >
                删除所有日志
              </Button>
            </Popconfirm>
            <Button type="primary" onClick={() => this.setExportModalVisible(true)}>
              导出
            </Button>
          </div>
          <div style={{ width: 290 }}>
            <Search
              placeholder={
                mode === 'operate' ? '请输入用户名/登录IP/操作描述搜索' : '请输入IP/登录结果搜索'
              }
              onSearch={this.onSearch}
              enterButton
            />
          </div>
        </div>
        <div style={{ marginBottom: 24, color: '#999EA8' }}>共“{count}”条日志</div>
        <Table
          dataSource={list}
          columns={columns}
          pagination={false}
          loading={{ spinning: loading, tip: '加载中' }}
          locale={{
            emptyText: (
              <Empty
                description={loading ? ' ' : '暂无数据'}
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            )
          }}
          rowKey="_id"
        />
        <div style={{ position: 'relative', height: 32, marginTop: 16 }}>
          <Pagination
            total={count}
            showTotal={count => `共 ${count} 条`}
            showSizeChanger
            current={this.state.filter.page}
            style={{ position: 'absolute', right: 0 }}
            onChange={this.onPageChange}
            onShowSizeChange={this.onShowSizeChange}
            showQuickJumper={true}
          />
        </div>
        <ExportModal
          visible={visible}
          onVisibleChange={this.setExportModalVisible}
          {...exportModalConfig}
        />
      </div>
    );
  }
}
OperationalLog.propTypes = {
  history: PropTypes.object,
  role: PropTypes.string
};

const mapStateToProps = state => {
  return {
    role: _.get(state, 'auth.user.role', '')
  };
};

export default connect(mapStateToProps)(OperationalLog);
